package com.example.book_recommend.service.impl;


import com.example.book_recommend.dao.SysTokenMapper;
import com.example.book_recommend.dao.UserMapper;
import com.example.book_recommend.entity.SysToken;
import com.example.book_recommend.entity.User;
import com.example.book_recommend.service.ShiroService;
import com.example.book_recommend.service.UserService;
import com.example.book_recommend.shiro.TokenGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Autowired
    private SysTokenMapper sysTokenMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 根据username查找用户
     *
     * @param username
     * @return User
     */
    @Override
    public User findByUsername(String username) {
        User user = userMapper.selectByUsername(username);
        return user;
    }

    //12小时后过期
    private final static int EXPIRE = 3600 * 12;

    @Override
    /**
     * 生成一个token
     *@param  [userId]
     *@return Result
     */
    public Map<String, Object> createToken(Integer userId) {
        Map<String, Object> result = new HashMap<>();
        String token = TokenGenerator.generateValue(userId.toString());
        SysToken sysToken = new SysToken();
        sysToken.setToken(token);
        sysToken.setUserId(userId);
        if(sysTokenMapper.selectByToken(token)==null){
            sysTokenMapper.insert(sysToken);
        }
        result.put("token", token);
        result.put("expire", EXPIRE);
        return result;
    }

    @Override
    public void logout(String token) {
        SysToken byToken = findByToken(token);
        if(byToken!=null){
            sysTokenMapper.deleteByPrimaryKey(byToken.getId());
        }
    }

    @Override
    public SysToken findByToken(String accessToken) {
        return sysTokenMapper.selectByToken(accessToken);
    }

    @Override
    public User findByUserId(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);
    }
}